<template>
  <div class="container">
    <header>
      <h1>{{ title }}</h1>
      <div class="header-controls">
        <div class="selection-mode">
          <button
            class="mode-btn"
            :class="{ active: selectionMode === 'single' }"
            @click="changeMode('single')"
          >单选模式</button>
          <button
            class="mode-btn"
            :class="{ active: selectionMode === 'multiple' }"
            @click="changeMode('multiple')"
          >多选模式</button>
        </div>
        <div class="search-box">
          <i class="fas fa-search search-icon"></i>
          <el-input clearable=""  type="text" :placeholder="searchPlaceholder" v-model="searchTerm" />
        </div>
      </div>
    </header>

    <div class="content" style="flex:1;min-height:0;" :id="getHeight">
      <div v-if="isShowCategorie" class="sidebar">
        <ul class="category-list">
          <li
            v-for="category in categories"
            :key="category.id"
            class="category-item"
            :class="{ active: selectedCategory === category.id }"
            @click="selectCategory(category.id)"
          >
            <i :class="category.icon"></i>
            {{ category.name }}
          </li>
        </ul>
      </div>

      <div class="main-content">
        <div class="devices-header">
          <h2>{{ listTitle }}</h2>
          <div class="devices-count">共找到 {{ filteredDevices.length }} 个设备</div>
        </div>

        <div class="devices-grid">
          <div
            v-for="device in filteredDevices"
            :key="device.id"
            class="device-card"
            :class="{ 
              selected: isDeviceSelected(device.id),
              disabled: device.disabled
            }"
            @click="!device.disabled && toggleDevice(device.id)"
          >
            <div class="checkbox-container">
              <div class="custom-checkbox"></div>
            </div>
            <div class="device-id">{{ device.id }}ssss</div>
            <div class="device-name">{{ device.name }}</div>
            <div class="device-category">{{ device.category }}</div>
            <div class="device-spec">{{ device.spec }}</div>
            <div class="device-status">
              <div class="status-dot" :class="`status-${device.status}`"></div>
              {{ getStatusText(device.status) }}
              <span
                v-if="device.disabled"
                class="disabled-text"
              >(不可选)</span>
            </div>
          </div>

          <div v-if="filteredDevices.length === 0" class="no-devices">{{ noDataText }}</div>
        </div>
         <!-- 添加分页组件 -->
        <div class="pagination-container" v-if="filteredDevices.length > 0">
          <el-pagination
            :current-page="pageOb.currentPage"
            :page-size="pageOb.pageSize"
            :total="filteredDevices.length"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
      </div>
    </div>

    <div class="footer">
      <div class="selected-info">
        已选择
        <span class="selected-count">{{ selectedDevices.length }}</span> 个设备
      </div>
      <div class="footer-buttons">
        <button class="cancel-btn" @click="handleCancel">取消</button>
        <button
          class="confirm-btn"
          :disabled="selectedDevices.length === 0"
          @click="confirmSelection"
        >{{ confirmButtonText }}</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "DeviceSelection",
  props: {
    // 基础配置
    title: {
      type: String,
      default: "选择设备"
    },
    isShowCategorie:{
      type: Boolean,
      default: false
    },
    listTitle: {
      type: String,
      default: "设备列表"
    },
    searchPlaceholder: {
      type: String,
      default: "搜索设备名称或编号..."
    },
    confirmButtonText: {
      type: String,
      default: "确定"
    },
    noDataText: {
      type: String,
      default: "未找到符合条件的设备"
    },

    // 数据
    categories: {
      type: Array,
      default: () => [
        { id: "all", name: "全部设备", icon: "fas fa-th-list" },
        { id: "demo", name: "演示用设备", icon: "fas fa-tv" },
        { id: "production", name: "生产设备", icon: "fas fa-industry" },
        { id: "electronic", name: "电子设备", icon: "fas fa-laptop" },
        { id: "transport", name: "运输工具", icon: "fas fa-truck" },
        { id: "instrument", name: "仪器及试验设备", icon: "fas fa-flask" },
        { id: "tools", name: "工具仪器及生产用品", icon: "fas fa-tools" },
        { id: "road", name: "一期扩建道路", icon: "fas fa-road" },
        { id: "land", name: "土地、使用权", icon: "fas fa-landmark" },
        { id: "decoration", name: "装修工程", icon: "fas fa-paint-roller" },
        { id: "office", name: "办公设备", icon: "fas fa-print" },
        { id: "other", name: "其他固定资产", icon: "fas fa-cube" },
        { id: "building", name: "建筑物", icon: "fas fa-building" },
        { id: "server1", name: "11111", icon: "fas fa-server" },
        { id: "server2", name: "2222222", icon: "fas fa-server" },
        { id: "server3", name: "333333", icon: "fas fa-server" },
        { id: "server4", name: "444444", icon: "fas fa-server" },
        { id: "server5", name: "555555", icon: "fas fa-server" },
        { id: "server", name: "x86服务器", icon: "fas fa-server" },
      ]
    },
    devices: {
      type: Array,
      default: () => [
        {
          id: "EQ-2023-001",
          name: "高精度示波器",
          category: "演示用设备",
          spec: "带宽: 1GHz, 采样率: 5GS/s, 通道: 4",
          status: "available"
        },
        {
          id: "EQ-2023-002",
          name: "工业机器人",
          category: "生产设备",
          spec: "负载: 20kg, 重复定位精度: ±0.05mm",
          status: "inuse",
          disabled: true
        },
        {
          id: "EQ-2023-003",
          name: "服务器集群",
          category: "x86服务器",
          spec: "CPU: 2×Xeon Gold, 内存: 256GB, 存储: 4TB SSD",
          status: "available"
        },
        {
          id: "EQ-2023-004",
          name: "恒温恒湿试验箱",
          category: "仪器及试验设备",
          spec: "温度范围: -40℃~150℃, 湿度范围: 20%~98%",
          status: "maintenance"
        }
      ]
    },

    // 初始值
    initialMode: {
      type: String,
      default: "single",
      validator: value => ["single", "multiple"].includes(value)
    },
    initialSelected: {
      type: Array,
      default: () => []
    },

    // 配置选项
    allowCancel: {
      type: Boolean,
      default: true
    },
    showStatus: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      pageOb:{
        currentPage:1,
        pageSize:10
      },
      selectionMode: this.initialMode,
      selectedCategory: "all",
      searchTerm: "",
      selectedDevices: [...this.initialSelected]
    };
  },
  computed: {
    filteredDevices() {
        console.log('111111111-filteredDevices',this.searchTerm);
      let filtered = this.devices;

      // 按分类筛选
      if (this.selectedCategory !== "all") {
        const categoryMap = {
          demo: "演示用设备",
          production: "生产设备",
          electronic: "电子设备",
          transport: "运输工具",
          instrument: "仪器及试验设备",
          tools: "工具仪器及生产用品",
          road: "一期扩建道路",
          land: "土地、使用权",
          decoration: "装修工程",
          office: "办公设备",
          other: "其他固定资产",
          building: "建筑物",
          server: "x86服务器"
        };

        const categoryName = categoryMap[this.selectedCategory];
        filtered = filtered.filter(device => device.category === categoryName);
      }

      // 按搜索词筛选
      if (this.searchTerm) {
        const term = this.searchTerm.toLowerCase();
        filtered = filtered.filter(
          device =>
            device.name.toLowerCase().includes(term) ||
            device.id.toLowerCase().includes(term)
        );
      }

      return filtered;
    },
    getHeight() {
        let upDownH = 0;
      this.$nextTick(() => {
        let head_h = document.getElementsByTagName("header");
        let foot_h = document.getElementsByClassName("footer");
        if (head_h) {
          upDownH = head_h[0].offsetHeight;
        }
        if (foot_h) {
          upDownH += foot_h[0].offsetHeight;
        }
        let content = document.querySelector(".content");
        if (content) {
          content.style.height = `calc(80vh - ${upDownH}px)`;
        }

        console.log("upDownH", upDownH);
      });
      //    console.log('2',foot_h[0].offsetHeight);
      return upDownH;
    }
  },
  watch: {
    initialSelected(newVal) {
      this.selectedDevices = [...newVal];
    },
    initialMode(newVal) {
      this.selectionMode = newVal;
    }
  },

  methods: {
    handleSizeChange(e){
      console.log('handleSizeChange-e',e);
    },
    handleCurrentChange(e){
      console.log('handleCurrentChange-e',e);
    },
 
    changeMode(mode) {
        console.log('11111111111');
      this.selectionMode = mode;

      // 如果是单选模式且当前选择了多个设备，只保留第一个
      if (mode === "single" && this.selectedDevices.length > 1) {
        this.selectedDevices = [this.selectedDevices[0]];
      }

      this.$emit("mode-change", mode);
    },

    selectCategory(categoryId) {
         console.log('222222222',categoryId);
      this.selectedCategory = categoryId;
      this.$emit("category-change", categoryId);
    },

    isDeviceSelected(deviceId) {
         console.log('3333333');
      return this.selectedDevices.includes(deviceId);
    },

    toggleDevice(deviceId) {
         console.log('444444');
      const device = this.devices.find(d => d.id === deviceId);
      if (device && device.disabled) return;

      if (this.selectionMode === "single") {
        // 单选模式：直接替换选中设备
        this.selectedDevices = [deviceId];
      } else {
        // 多选模式：切换选中状态
        const index = this.selectedDevices.indexOf(deviceId);
        if (index > -1) {
          this.selectedDevices.splice(index, 1);
        } else {
          this.selectedDevices.push(deviceId);
        }
      }

      this.$emit("selection-change", this.selectedDevices);
    },

    getStatusText(status) {
         console.log('5555555555');
      const statusMap = {
        available: "可用",
        inuse: "使用中",
        maintenance: "维护中"
      };
      return statusMap[status] || "未知";
    },

    confirmSelection() {
         console.log('66666666666');
      if (this.selectedDevices.length === 0) return;

      const selectedDevicesData = this.devices.filter(device =>
        this.selectedDevices.includes(device.id)
      );

      this.$emit("confirm", {
        deviceIds: this.selectedDevices,
        devices: selectedDevicesData,
        mode: this.selectionMode
      });
    },

    handleCancel() {
         console.log('7777777777');
      this.$emit("cancel");
    },

    // 公共方法：清除选择
    clearSelection() {
         console.log('8888888888');
      this.selectedDevices = [];
      this.$emit("selection-change", this.selectedDevices);
    },

    // 公共方法：设置选择
    setSelection(deviceIds) {
         console.log('99999999999');
      if (this.selectionMode === "single" && deviceIds.length > 1) {
        console.warn("单选模式下只能选择一个设备，将使用第一个设备ID");
        this.selectedDevices = [deviceIds[0]];
      } else {
        this.selectedDevices = [...deviceIds];
      }
      this.$emit("selection-change", this.selectedDevices);
    }
  }
};
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Segoe UI", "Microsoft YaHei", sans-serif;
}

.container {
  max-height: 80vh;
  width: 70%;
  max-width: 1000px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

header {
  padding: 24px 30px;
  border-bottom: 1px solid #eaeef2;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #095b90, #6a82fb);
  color: white;
}

h1 {
  font-size: 24px;
  font-weight: 600;
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 20px;
}

.selection-mode {
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 6px;
  padding: 5px;
}

.mode-btn {
  padding: 8px 16px;
  border: none;
  background: transparent;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.mode-btn.active {
  background: rgba(255, 255, 255, 0.3);
  font-weight: 500;
}

.search-box {
  position: relative;
  width: 300px;
}

.search-box el-input {
  width: 100%;
  padding: 12px 20px 12px 45px;
  border: none;
  border-radius: 30px;
  background: rgba(255, 255, 255, 0.9);
  font-size: 14px;
  transition: all 0.3s;
}

.search-box el-input:focus {
  outline: none;
  box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.5);
  background: white;
}

.search-icon {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #6a82fb;
}

.content {
  display: flex;
  min-height: 500px;
  box-sizing: border-box;
}

.sidebar {
  width: 260px;
  background: #f8fafc;
  border-right: 1px solid #eaeef2;
  padding: 25px 0;
  overflow-y: auto;
}

.category-list {
  list-style: none;
}

.category-item {
  padding: 14px 30px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  font-size: 15px;
  color: #555;
}

.category-item:hover {
  background: #edf2ff;
  color: #6a82fb;
}

.category-item.active {
  background: #e8eeff;
  color: #6a82fb;
  border-right: 3px solid #6a82fb;
  font-weight: 500;
}

.category-item i {
  margin-right: 12px;
  font-size: 18px;
}

.main-content {
  flex: 1;
  padding: 25px 30px;
  overflow-y: auto;
}

.devices-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.devices-count {
  color: #666;
  font-size: 15px;
}

.devices-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.device-card {
  background: white;
  border-radius: 10px;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
  padding: 20px;
  transition: all 0.3s;
  border: 1px solid #eaeef2;
  position: relative;
}

.device-card:not(.disabled) {
  cursor: pointer;
}

.device-card:not(.disabled):hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.device-card.selected {
  border-color: #6a82fb;
  box-shadow: 0 5px 15px rgba(106, 130, 251, 0.2);
}

.device-card.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.checkbox-container {
  position: absolute;
  top: 15px;
  right: 15px;
}

.custom-checkbox {
  width: 22px;
  height: 22px;
  border: 2px solid #ddd;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.device-card.selected .custom-checkbox {
  background: #6a82fb;
  border-color: #6a82fb;
}

.device-card.disabled .custom-checkbox {
  border-color: #ccc;
}

.custom-checkbox::after {
  content: "";
  width: 5px;
  height: 10px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg) scale(0);
  transition: all 0.2s;
}

.device-card.selected .custom-checkbox::after {
  transform: rotate(45deg) scale(1);
}

.device-id {
  font-size: 13px;
  color: #888;
  margin-bottom: 5px;
  padding-right: 30px;
}

.device-name {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 10px;
  color: #333;
  padding-right: 30px;
}

.device-category {
  display: inline-block;
  background: #edf2ff;
  color: #6a82fb;
  padding: 4px 10px;
  border-radius: 20px;
  font-size: 12px;
  margin-bottom: 12px;
}

.device-spec {
  font-size: 14px;
  color: #666;
  margin-bottom: 15px;
  line-height: 1.5;
}

.device-status {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: #888;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 6px;
}

.status-available {
  background: #4caf50;
}

.status-inuse {
  background: #ff9800;
}

.status-maintenance {
  background: #f44336;
}

.disabled-text {
  color: #f44336;
  margin-left: 8px;
  font-size: 12px;
}

.footer {
  padding: 20px 30px;
  border-top: 1px solid #eaeef2;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f8fafc;
}

.selected-info {
  color: #666;
  font-size: 14px;
}

.selected-count {
  font-weight: 600;
  color: #6a82fb;
}

.footer-buttons {
  display: flex;
  gap: 12px;
}

.cancel-btn {
  background: #f8f9fa;
  color: #666;
  border: 1px solid #ddd;
  padding: 12px 24px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
}

.cancel-btn:hover {
  background: #e9ecef;
  border-color: #adb5bd;
}

.confirm-btn {
  background: #6a82fb;
  color: white;
  border: none;
  padding: 12px 30px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 15px;
  font-weight: 500;
  transition: all 0.2s;
}

.confirm-btn:hover:not(:disabled) {
  background: #5a72e5;
  box-shadow: 0 4px 10px rgba(106, 130, 251, 0.3);
}

.confirm-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
  box-shadow: none;
}

.no-devices {
  text-align: center;
  padding: 40px;
  color: #888;
  font-size: 16px;
  grid-column: 1 / -1;
  
 
}

/* @media (max-width: 768px) {
  .content {
    flex-direction: column;
    max-height: none;
  }

  .sidebar {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid #eaeef2;
    max-height: 200px;
  }

  .devices-grid {
    grid-template-columns: 1fr;
  }

  .header-controls {
    flex-direction: column;
    gap: 10px;
    align-items: flex-end;
  }

  .search-box {
    width: 200px;
  }

  .footer {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }

  .footer-buttons {
    justify-content: flex-end;
  }
} */
</style>